<template>
    <div class="wrap">
        <div class="wrap-util">
            <a-button class="mr-10" :type="isSelectAll?'':'dashed'" @click="selectAll()">
                <BarsOutlined/>
                全选
            </a-button>
            <a-button type="primary" class="mr-10" @click="showAddModal">
                <PlusCircleOutlined/>
                新增
            </a-button>
            <a-button :disabled="!isHasSelect" type="danger" class="mr-10" @click="showDeleteConfirm">
                <DeleteOutlined/>
                删除
            </a-button>
        </div>
        <div class="table">
            <table>
                <thead>
                <tr>
                    <th>#</th>
                    <th>标题</th>
                    <th>封面</th>
                    <th>点击量</th>
                    <th>发表时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="(item,index) in blogList">
                    <td>
                        <a-checkbox :checked="selectedIds.has(item.id)"
                                    @change="selectedBlogIds(item.id,$event)"/>
                    </td>
                    <td style="text-align: left;">{{item.title}}</td>
                    <td>
                        <a-image
                                :width="80"
                                :src="item.cover"
                                fallback=""
                        >
                        </a-image>
                    </td>
                    <td>
                        {{item.views}}
                    </td>
                    <td>
                        {{parseDatetime(item.created)}}
                    </td>
                    <td>
                        <a @click="editBlog(item.id)">
                            <EditOutlined/>
                            编辑</a>
                        <a-divider type="vertical"/>
                        <a-popconfirm @confirm="delBlog(item.id)" title="确定删除？" ok-text="删除" cancel-text="取消">
                            <a>
                                <DeleteOutlined/>
                                删除</a>
                        </a-popconfirm>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
        <div class="pagination">
            <a-pagination
                    align="center"
                    :show-total="total => `共 ${total} 条数据`"
                    show-quick-jumper
                    show-size-changer
                    :page-size-options="pageSizeOptions"
                    v-model:current="current"
                    v-model:pageSize="pageSize"
                    :total="total"
                    @showSizeChange="onShowSizeChange"
            >
                <template #buildOptionText="props">
                    <span v-if="props.value !== '100'">{{ props.value }}条/页</span>
                    <span v-else>全部显示</span>
                </template>
            </a-pagination>
        </div>

        <!--添加模态框-->
        <a-modal v-model:visible="addModalVisible"
                 cancelText="取消"
                 okText="确定"
                 width="1000px"
                 title="编辑"
                 centered
                 :confirmLoading="false"
                 @ok="addBlog">
            <div class="mb-10">
                <a-input v-model:value="blog.title" placeholder="标题"/>

            </div>
            <div class="mb-10">
                <a-row>
                    <a-col :span="6">
                        <a-upload
                                name="file"
                                :multiple="false"
                                :action="coverUploadPath"
                                :headers="headers"
                                :showUploadList="false"
                                @change="handleChange"
                        >
                            <a-button>
                                <upload-outlined></upload-outlined>
                                本地上传封面图片
                            </a-button>
                        </a-upload>
                    </a-col>
                    <a-col :span="18">
                        <a-input v-model:value="blog.cover" placeholder="封面URL"/>
                    </a-col>
                </a-row>
            </div>
            <v-md-editor v-model="blog.content" height="400px"></v-md-editor>
        </a-modal>
    </div>
</template>
<script>
    import {defineComponent, toRefs, watch, reactive, onBeforeMount, createVNode} from 'vue';
    import {getBlogList, getBlogById, updateBlogById} from "../../../api/comms";
    import {
        ExclamationCircleOutlined,
        PlusCircleOutlined,
        DeleteOutlined,
        BarsOutlined,
        EditOutlined,
        UploadOutlined,
    } from '@ant-design/icons-vue';
    import {notification, Modal, message} from "ant-design-vue"
    import {getUserInfo, parseDatetime, showResp} from "../../../utils/util";
    import {adminAddBlog, adminDelBlog} from "../../../api/admin";

    export default defineComponent({
        name: "Article",
        setup() {
            const state = reactive({
                pageSizeOptions: ['5', '10', '20', '50', '100'],
                blogList: [],
                current: 1,
                pageSize: 10,
                total: 0,
                selectedIds: new Set(),
                isHasSelect: false,
                isSelectAll: false,
                addModalVisible: false,
                blog: {
                    title: "",
                    cover: "",
                },
                editId: "",//当前编辑的Id
                headers: {
                    token: ""
                },
                coverUploadPath: ""
            });
            const onShowSizeChange = (current, pageSize) => {
                console.log(current, pageSize);
            };
            const blogList = () => {
                getBlogList(state.current, state.pageSize)
                    .then(resp => {
                        state.total = resp.data.total;
                        state.blogList = resp.data.records;
                        state.blogList.forEach(item => {
                            if (!item.cover.startsWith("http")) {
                                item.cover = window.apiPath + item.cover;
                            }
                        })
                    })
            }
            const selectedBlogIds = (id, e) => {
                let selected = e.target.checked;
                let hasVal = state.selectedIds.has(id);
                if (selected) {
                    // 添加
                    if (!hasVal) {
                        state.selectedIds.add(id);
                    }
                    state.isHasSelect = true;
                } else {
                    if (hasVal) {
                        state.selectedIds.delete(id);
                    }
                    if (state.selectedIds.size == 0) {
                        state.isHasSelect = false;
                    }
                }
            }
            //全选（封装）
            const selectAll = () => {
                state.isSelectAll = !state.isSelectAll;
                if (state.isSelectAll) {
                    state.blogList.forEach(blog => {
                        state.selectedIds.add(blog.id)
                    });
                    state.isHasSelect = true;
                } else {
                    state.selectedIds.clear();
                    state.isHasSelect = false;
                }
            }
            //多选删除询问
            const showDeleteConfirm = () => {
                Modal.confirm({
                    title: '确认',
                    icon: createVNode(ExclamationCircleOutlined),
                    content: '你确定要删除选中的文章吗？',
                    okText: '我确定',
                    okType: 'danger',
                    cancelText: '点错了',
                    onOk() {
                        message.success("已删除")
                    },

                    onCancel() {
                        message.info("已取消删除")
                    },
                });
            }
            //展示博客模态框
            const showAddModal = () => {
                clearAddModal();
                state.addModalVisible = true;
            };

            const clearAddModal = () => {
                state.blog = {
                    title: "",
                    cover: "",
                    content: "",
                };
            };

            //增加或者修改
            const addBlog = () => {
                let {title, cover, content} = state.blog;
                if (title == "" || content == "") {
                    message.warn("标题、内容不能为空！")
                    return false;
                }
                //判断是否编辑
                if (state.editId != "") {
                    updateBlogById(state.editId, title, cover, content).then(resp => {
                        showResp(resp);
                        state.id = "";
                        blogList();
                        state.addModalVisible = false;
                    })
                    return false;
                }
                adminAddBlog(title, cover, content)
                    .then(resp => {
                        if (resp.code == 200) {
                            message.success(resp.message);
                            blogList();
                        } else {
                            message.error(resp.message)
                        }
                    })
                state.addModalVisible = false;
                clearAddModal();
            };
            //删除博客
            const delBlog = id => {
                adminDelBlog(id)
                    .then(resp => {
                        showResp(resp);
                        blogList();
                    })
            }
            //编辑查看博客
            const editBlog = id => {
                getBlogById(id)
                    .then(resp => {
                        if (resp.code == 200) {
                            state.blog.title = resp.data.title
                            state.blog.cover = resp.data.cover
                            state.blog.content = resp.data.content
                            state.editId = id;
                            console.log(state.editId)
                            state.addModalVisible = true;
                        }
                    })
            }

            const handleChange = info => {
                const status = info.file.status;
                if (status !== 'uploading') {
                    //console.log(info.file, info.fileList);
                }
                if (status === 'done') {
                    message.success(`${info.file.name} 文件上传成功.`);
                    console.log(info.file.response.data.relativePath);
                    state.blog.cover = info.file.response.data.relativePath;
                } else if (status === 'error') {
                    message.error(`${info.file.name} 文件上传失败.`);
                }
            }


            watch(() => state.pageSize, () => {
                blogList();
            });
            watch(() => state.current, () => {
                blogList();
            });
            onBeforeMount(() => {
                blogList();

                state.coverUploadPath = window.apiPath + "/file/imageUpload"
                state.headers.token = getUserInfo().token;
            });
            return {
                ...toRefs(state),
                onShowSizeChange,
                selectedBlogIds,
                selectAll,
                showDeleteConfirm,
                showAddModal,
                parseDatetime,
                addBlog,
                delBlog,
                editBlog,
                handleChange
            };
        },
        components: {
            PlusCircleOutlined,
            DeleteOutlined,
            BarsOutlined,
            EditOutlined,
            UploadOutlined
        },
    });
</script>

<style lang="less">
    .mr-10 {
        margin-right: 10px;
    }

    .mb-10 {
        margin-bottom: 10px;
    }
</style>